﻿using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System.Reflection;

namespace PmSoft.Quartz;

public static class QuartzServiceCollectionExtensions
{
    public static void AddQuartz(this IServiceCollection services, RunAtServer server = RunAtServer.Any)
    {
        services.AddSingleton<QuartzJobRunner>();
        services.AddSingleton<IJobFactory, SingletonJobFactory>();
        services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
        services.AddJobs(server);
        services.AddHostedService<QuartzHostedService>();
    }


    static void AddJobs(this IServiceCollection services, RunAtServer server)
    {

        //IEnumerable<Assembly> assemblyList = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(Assembly.Load);
        IEnumerable<Assembly> assemblyList = AppDomain.CurrentDomain.GetAssemblies();
        foreach (var assembly in assemblyList)
        {
            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                var attribute = type.GetCustomAttribute<JobDescriptionAttribute>();
                if (attribute != null && (attribute.AtServer == RunAtServer.Any
                        || server == attribute.AtServer))
                {
                    services.AddScoped(type);
                    services.AddSingleton(new JobDescriptor(type, attribute.CronExpression));
                }
            }
        }
    }

}
